package com.dd.common.enums;


import com.dd.common.config.GlobalConfig;

/**
 * 文件类型枚举
 *
 * @author cheng
 */
public enum FileTypeEnum {

    IMAGE(1, "image", GlobalConfig.uploadImageExt, GlobalConfig.uploadImageMimeTypes),
    VIDEO(2, "video", GlobalConfig.uploadVideoExt, GlobalConfig.uploadVideoMimeTypes),
    AUDIO(3, "audio", GlobalConfig.uploadAudioExt, GlobalConfig.uploadAudioMimeTypes),
    DOC(4, "doc", GlobalConfig.uploadDocExt, GlobalConfig.uploadDocMimeTypes),
    OTHER(5, "other",  new String[]{},  new String[]{});
    private final int code;
    private final String msg;
    private final String[] extensions;
    private final String[] mimeTypes;
    FileTypeEnum(int code, String msg, String[] extensions, String[] mimeTypes) {
        this.code = code;
        this.msg = msg;
        this.extensions = extensions;
        this.mimeTypes = mimeTypes;
    }

    public int getCode() {
        return this.code;
    }
    public String getMsg() {
        return msg;
    }
    public String[] getExtensions() { return extensions; }
    public String[] getMimeTypes() { return mimeTypes; }


    // 添加根据 code 查找枚举的方法
    public static FileTypeEnum fromCode(int code) {
        for (FileTypeEnum type : FileTypeEnum.values()) {
            if (type.getCode() == code) {
                return type;
            }
        }
        return OTHER; // 默认回退
    }

    // 静态方法：根据扩展名或 MIME 类型推断类型
    public static FileTypeEnum resolve(String extension, String mimeType) {
        // 先用 MIME 类型判断（更准确）
        for (FileTypeEnum type : FileTypeEnum.values()) {
            if (type == OTHER) continue;
            for (String mime : type.mimeTypes) {
                if (mime.equalsIgnoreCase(mimeType)) {
                    return type;
                }
            }
        }

        // MIME 不确定时，用扩展名兜底
        if (extension != null) {
            for (FileTypeEnum type : FileTypeEnum.values()) {
                if (type == OTHER) continue;
                for (String ext : type.extensions) {
                    if (ext.equalsIgnoreCase(extension)) {
                        return type;
                    }
                }
            }
        }

        return OTHER;
    }
}
